
package com.it155.bailianai.demos.web;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/bailian")
public class ApiController {

    public String callWithMessage(String city)
            throws NoApiKeyException, ApiException, InputRequiredException {
        Generation gen = new Generation();
        List<Message> messages = new ArrayList<>();
        Message systemMsg =
                Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content("请根据以下指定城市，给我推荐十道地方美食，仅输出美食名称即可，格式形如{\"北京烤鸭\",\"西湖牛肉羹\",\"脆皮鸡\"}，美食字段为foodName，城市为："+city).build();
        messages.add(systemMsg);
        messages.add(userMsg);
        GenerationParam param =
                GenerationParam.builder().model(Generation.Models.QWEN_TURBO).messages(messages)
                        .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                        .build();
        param.setApiKey("换成你的API-KEY");
        GenerationResult result = gen.call(param);
        return JsonUtils.toJson(result);
    }

    @RequestMapping("/api")
    public String gen(String city){
        try {
            return callWithMessage(city);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            return e.getMessage();
        }
    }
}
